/**
 * Form Layout by Karla.
 * Functional coding (to login) by Lidiya.
 */

package Forms;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

import javax.swing.BorderFactory;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import teComponents.teJButton;
import teComponents.teJFrame;
import teComponents.teJinternalFrame;
import teComponents.teJLabel;
import teComponents.teJLabelWarning;
import teComponents.teJTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;

import Classes.DB_utils;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class LoginForm extends teComponents.teJinternalFrame {
	private teJLabel lblUser;
	private teJLabel lblPwd;
	private teJTextField txtUser;
	private teJButton btnLogin;
	private teJLabel lblForm;
	private teJLabelWarning lblWarning;
	private JPasswordField txtPassword;
	
	private teJFrame prnt;
	private DB_utils ut;

	
	
	public LoginForm(teJFrame fr) {
		super();
		prnt = fr;
		initGUI();
	}
	
	private DB_utils setUtils()
	{
	    if(ut == null)
	    {
	    	ut = new DB_utils();
	    }
	    return ut;
	}
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setTitle("Login");
			{
				lblUser = new teJLabel();
				getContentPane().add(lblUser);
				lblUser.setText("User Name:");
				lblUser.setBounds(49, 73, 75, 14);
			}
			{
				lblPwd = new teJLabel();
				getContentPane().add(lblPwd);
				lblPwd.setText("Password:");
				lblPwd.setBounds(58, 103, 66, 14);
			}
			{
				txtUser = new teJTextField();
				getContentPane().add(txtUser);
				txtUser.setBounds(164, 69, 156, 18);
			}
			{
				txtPassword = new JPasswordField();
			
				getContentPane().add(txtPassword);
				txtPassword.setBounds(164, 99, 156, 18);
				txtPassword.setForeground(new java.awt.Color(43,32,3));
				txtPassword.setBackground(new java.awt.Color(255,255,255));
				txtPassword.setSelectionColor(new java.awt.Color(212,251,248)); //#D3FBF8
				txtPassword.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, new java.awt.Color(147,188,12), new java.awt.Color(243,250,218), new java.awt.Color(92,69,5), new java.awt.Color(92,69,5)));
				txtPassword.setFont(new java.awt.Font("SansSerif",0,12));
				txtPassword.setHorizontalAlignment(SwingConstants.LEFT);
			}
			{
				lblWarning = new teJLabelWarning();
				getContentPane().add(lblWarning);
				lblWarning.setBounds(49, 179, 271, 35);
			}
			{
				lblForm = new teJLabel();
				getContentPane().add(lblForm);
				lblForm.setText("Please enter your login information");
				lblForm.setBounds(49, 23, 271, 22);
			}
			{
				btnLogin = new teJButton();
				getContentPane().add(btnLogin);
				btnLogin.setText("Login");
				btnLogin.setBounds(220, 142, 100, 25);
				btnLogin.setToolTipText("Log in to the database to maintain Agents, Agencies, Customers, Products, Suppliers, and Packages.");
				btnLogin.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) 
					{
						if(!(txtUser.getText().isEmpty()) && (!(txtPassword.getPassword().equals(null))))
						{
							MainMDIForm mf = (MainMDIForm)prnt;
							String res = processLogIn();
							if(!res.isEmpty())
							{							
								mf.setCardStr(res);
								setVisible(false);
							}
						}
						else
						{
							txtUser.setText("");
							txtPassword.setText("");
						}
					}
				});
			}
			pack();
			this.setSize(398, 271);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	private String  processLogIn()
	{
		
		boolean present = false;
		String pswd = "";
		int agId =0;
		String cardId = "";
		String agPos = "";
		
		//get record from the table AGENTLOGIN
		String sql = "SELECT * FROM  AGENTLOGIN WHERE USERNAME = '" + txtUser.getText() +"'";
		System.out.println(sql);
		setUtils().setDbConnection();
		ResultSet rs = ut.getRs(sql);
		try 
		{
			
			while (rs.next())
			 {
			      agId = rs.getInt(1);
			      pswd = rs.getString(3);
			      present = true;
			 }
						
	    }
		catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//UserName present
		if(present)
		{
			//check password
		    boolean eq =checkPswd(pswd);
		    if(eq)
			{
		          sql = "SELECT * FROM  AGENTS WHERE AGENTID = '" + agId +"'";
		          System.out.println(sql);
		          present = false;
		  		  rs = ut.getRs(sql);
		  		  try 
		  		  {
		  			 while (rs.next())
		  			 {
		  				 agPos = rs.getString("AGTPOSITION");
		  			     present = true;
		  			  }
		  		   }
		  		   catch (SQLException e) 
				   {
					         // TODO Auto-generated catch block
					  e.printStackTrace();
				    }
		  		     //we done with database
		  		    ut.closeDbConnection();
		  		    
		  		    if(present)
		  		   {
		  			   if(agPos.equals("Senior Agent"))
		  			   {
		  			 	cardId = "managerCard";
		  			   }
		  			   else
		  			   {
		  				  cardId = "employeeCard";
		  			   }
		  		   }
		  		   else
		  		   {
		  			 //System.out.println("Record in AGENTS table not found");
		  			   lblWarning.setText("Database is offline.");
		  		   }
		  		 
			     }
				  else
				  {
					  //System.out.println("Password does not match");
					  lblWarning.setText("Login failed.");
				  }
		     }
			else
			{
				//System.out.println("Username does not exist in our database");
				lblWarning.setText("Login failed.");
			}
	    txtUser.setText("");
	    txtPassword.setText("");
		return cardId;
	}

	private boolean checkPswd(String pswd)
	{
		boolean isCorrect;
		char [] chPswd = new char[pswd.length()];
		char [] input = txtPassword.getPassword();
		
		pswd.getChars(0, pswd.length(), chPswd, 0);
		//compare passwords
		 if (input.length != chPswd.length) 
		 {
		     isCorrect = false;
		     //System.out.println("Password doesnot match");
		     lblWarning.setText("Login failed.");
		 } 
		 else 
		 {
		     isCorrect = Arrays.equals (input, chPswd);
		 }
		
		return isCorrect;
	}
}
